package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.dto.PurchaseDemandAddDTO;
import com.intelligent.dto.PurchaseDemandQueryDTO;
import com.intelligent.mapper.ProductMapper;
import com.intelligent.mapper.PurchaseDemandMapper;
import com.intelligent.mapper.UnitMapper;
import com.intelligent.pojo.Product;
import com.intelligent.pojo.PurchaseDemand;
import com.intelligent.pojo.Unit;
import com.intelligent.service.PurchaseDemandService;
import com.intelligent.vo.PurchaseDemandVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 86188
* @description 针对表【purchase_demand(采购需求信息表)】的数据库操作Service实现
* @createDate 2025-09-02 10:11:39
*/
@Service
public class PurchaseDemandServiceImpl extends ServiceImpl<PurchaseDemandMapper, PurchaseDemand>
    implements PurchaseDemandService{

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UnitMapper unitMapper;

    @Override
    public IPage<PurchaseDemandVO> pageList(PurchaseDemandQueryDTO queryDTO) {
        // 1. 参数校验和默认值设置
        int pageNum = queryDTO.getPageNum() == null ? 1 : queryDTO.getPageNum();
        int pageSize = queryDTO.getPageSize() == null ? 10 : queryDTO.getPageSize();
        Page<PurchaseDemand> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        LambdaQueryWrapper<PurchaseDemand> wrapper = new LambdaQueryWrapper<>();

        // 采购需求单号模糊查询
        if (StringUtils.isNotBlank(queryDTO.getDemandNo())) {
            wrapper.like(PurchaseDemand::getDemandNo, queryDTO.getDemandNo());
        }

        // 采购状态精确查询
        if (queryDTO.getPurchaseStatus() != null) {
            wrapper.eq(PurchaseDemand::getPurchaseStatus, queryDTO.getPurchaseStatus());
        }

        // 生产计划工单编号模糊查询（通过生产计划ID查询）
        if (StringUtils.isNotBlank(queryDTO.getProductionWorkOrder())) {
            // 这里假设生产计划工单编号与生产计划ID有关联
            // 实际实现中可能需要关联生产计划表
            wrapper.like(PurchaseDemand::getProductionPlanId, queryDTO.getProductionWorkOrder());
        }


        // 3. 执行分页查询
        IPage<PurchaseDemand> entityPage = this.page(page, wrapper);

        // 4. 如果没有数据，直接返回空结果
        if (entityPage.getTotal() == 0) {
            Page<PurchaseDemandVO> empty = new Page<>(page.getCurrent(), page.getSize(), 0);
            empty.setRecords(Collections.emptyList());
            return empty;
        }

        // 5. 批量预取关联数据
        // 获取所有产品ID和单位ID
        List<Long> productIds = entityPage.getRecords().stream()
                .flatMap(pd -> Arrays.stream(new Long[]{pd.getProductId(), pd.getProductionId()}))
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 查询产品信息
        final Map<Long, Product> productMap;
        if (!productIds.isEmpty()) {
            productMap = productMapper.selectList(new QueryWrapper<Product>().in("product_id", productIds))
                    .stream().collect(Collectors.toMap(Product::getProductId, p -> p, (k1, k2) -> k1));
        } else {
            productMap = Collections.emptyMap();
        }

        // 获取所有单位ID
        List<Long> unitIds = productMap.values().stream()
                .map(Product::getUnitId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 查询单位信息
        final Map<Long, Unit> unitMap;
        if (!unitIds.isEmpty()) {
            unitMap = unitMapper.selectList(new QueryWrapper<Unit>().in("unit_id", unitIds))
                    .stream().collect(Collectors.toMap(Unit::getUnitId, u -> u, (k1, k2) -> k1));
        } else {
            unitMap = Collections.emptyMap();
        }

        // 6. 组装VO数据
        List<PurchaseDemandVO> records = entityPage.getRecords().stream().map(pd -> {
            PurchaseDemandVO vo = new PurchaseDemandVO();

            // 基本信息
            vo.setId(pd.getId());
            vo.setDemandNo(pd.getDemandNo());
            vo.setPurchaseStatus(pd.getPurchaseStatus());
            vo.setRemark(pd.getRemark());

            // 设置采购状态文本
            vo.setPurchaseStatusText(getPurchaseStatusText(pd.getPurchaseStatus()));

            // 生产计划工单编号
            vo.setProductionWorkOrder(String.format("SCJH%08d", pd.getProductionPlanId() == null ? 0 : pd.getProductionPlanId()));

            // 生产产品信息
            Product product = productMap.get(pd.getProductId());
            if (product != null) {
                vo.setProductCode(product.getProductCode());
                vo.setProductName(product.getProductName());
                vo.setSpecification(product.getSpecification());
                vo.setCategory(product.getCategory());
                vo.setCategoryText(getCategoryText(product.getCategory()));

                // 设置单位信息
                Unit unit = unitMap.get(product.getUnitId());
                if (unit != null) {
                    vo.setUnitName(unit.getUnitName());
                }

                // 设置库存信息
                vo.setAvailableStock(product.getCurrentStock());
            }

            // 所需物料信息
            Product material = productMap.get(pd.getProductionId());
            if (material != null) {
                vo.setMaterialCode(material.getProductCode());
                vo.setMaterialName(material.getProductName());
            }

            // 设置默认的数量信息（实际项目中这些数据可能来自其他表）
            vo.setRequiredQuantity(new java.math.BigDecimal("0"));
            vo.setNetDemand(new java.math.BigDecimal("0"));
            vo.setToBePurchased(new java.math.BigDecimal("0"));
            vo.setPurchasedAndStored(new java.math.BigDecimal("0"));

            return vo;
        }).collect(Collectors.toList());

        // 7. 构建返回结果
        Page<PurchaseDemandVO> voPage = new Page<>(entityPage.getCurrent(), entityPage.getSize(), entityPage.getTotal());
        voPage.setRecords(records);
        return voPage;
    }

    @Override
    public boolean add(PurchaseDemandAddDTO addDTO) {
        if (addDTO == null) return false;
        PurchaseDemand entity = new PurchaseDemand();
        entity.setDemandNo(StringUtils.isNotBlank(addDTO.getDemandNo()) ? addDTO.getDemandNo() : generateDemandNo());
        entity.setPurchaseStatus(addDTO.getPurchaseStatus() == null ? 0 : addDTO.getPurchaseStatus());
        entity.setProductionPlanId(addDTO.getProductionPlanId());
        entity.setProductId(addDTO.getProductId());
        entity.setProductionId(addDTO.getProductionId());
        entity.setRemark(addDTO.getRemark());
        return this.save(entity);
    }

    /**
     * 生成采购需求单号
     */
    private String generateDemandNo() {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        LambdaQueryWrapper<PurchaseDemand> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(PurchaseDemand::getDemandNo, "CGXQ" + date);
        long count = this.count(wrapper);
        String seq = String.format("%04d", count + 1);
        return "CGXQ" + date + seq;
    }

    /**
     * 获取采购状态文本
     */
    private String getPurchaseStatusText(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 0: return "待采购入库";
            case 1: return "部分采购入库";
            case 2: return "全部采购入库";
            default: return "未知状态";
        }
    }

    /**
     * 获取分类文本
     */
    private String getCategoryText(Integer category) {
        if (category == null) return "";
        switch (category) {
            case 0: return "成品";
            case 1: return "半成品";
            case 2: return "原材料";
            default: return "未知分类";
        }
    }
}




